package cn.infinite.security.handler;

import cn.easier.club.base.dto.ResultInfo;
import cn.infinite.security.configuration.SecurityBasicProperties;
import cn.infinite.security.http.AsyncRefererSavedRequest;
import cn.infinite.security.http.HttpProtocolExpand;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足处理
 */
@Slf4j
@ConditionalOnProperty(prefix = "spring.security", name = "access-denied-url")
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private SecurityBasicProperties securityBasicProperties;

    private PortResolver portResolver = new PortResolverImpl();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException
            accessDeniedException) throws IOException, ServletException {
        String accept = request.getHeader(HttpHeaders.ACCEPT);
        String callBackUrl = request.getHeader(HttpProtocolExpand.AUTH_FINALLY_LOCATION);

        log.info("browser set callBackUrl after authenticate success. => {}", callBackUrl);

        if (StringUtils.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE, accept) || StringUtils.containsIgnoreCase
                (accept, MediaType.TEXT_HTML_VALUE)) {
            log.info("accept response content-type is text/html; uri =>{}", request.getRequestURI());
            response.sendRedirect(this.securityBasicProperties.getAccessDeniedUrl());
        } else {
            log.info("async request. accessDenied.");
            if (StringUtils.isNotBlank(callBackUrl)) {
                SavedRequest savedRequest = new AsyncRefererSavedRequest(request, this.portResolver, callBackUrl);
                request.getSession().setAttribute(HttpProtocolExpand.SAVED_REQUEST, savedRequest);
            }
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
            ResultInfo<String> resultInfo = new ResultInfo<>("error", "权限不足", null);
            response.getWriter().write(JSON.toJSONString(resultInfo));
            response.getWriter().close();
        }
    }
}
